<!DOCTYPE html>
<html height100 xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <div th:replace="authority/common/currency/head"></div>
    <style type="text/css">
        h1, h2, h3 {
            padding: 10px 0;
        }

        /*a {*/
        /*text-align: right;*/
        /*font-size: 18px;*/
        /*color: #1C86EE;*/
        /*}*/

        .tree_contianer {
            width: 100%;
            height: 100%;
            color: #0C0C0C;
            /*border: 1px solid #9C9C9C;*/
            overflow: auto;
            padding: 5px 0 25px 0;
            margin-bottom: 10px;
            /*background-color: #fff;*/
        }

        .icon-hide {
            display: none;
        }

        .nav-tree-div {
            white-space: nowrap;
        }

        /*.tree_contianer .nav-tree-item {*/
        /*padding-left: 0;*/
        /*}*/

        /*.tree_contianer .nav-tree-div {*/
        /*padding-left: 15px;*/
        /*}*/

        .zsa-nav {
            background: #FFF;
            overflow: hidden;
            height: 100%;
            padding-bottom: 75px;
            border-right: 1px solid #e6e6e6;
        }

        .zsa-nav form {
            height: 100%;
        }

        .zsa-nav .layui-this {
            background-color: #fff;
        }

        .zsa-nav .zsa-nav-title {
            color: #666;
            font-size: 20px;
            padding: 0 20px;
            border-bottom: 1px solid #e6e6e6;
        }

        .zsa-page-content {
            padding-left: 199px;
        }

        .zsa-page-content .layui-tab {
            margin: 0;
        }

        .zsa-page-content .layui-tab-title {
            height: 44px;
        }

        .zsa-page-content .layui-tab-title li {
            line-height: 48px;
        }

        .zsa-page-content .layui-tab-title .layui-this:after {
            height: 40px;
            top: 5px;
        }

        .zsa-page-content .x-so, .zsa-page-content xblock {
            text-align: left;
            margin-bottom: 5px;
        }

        .zsa-page-content xblock {
            margin-bottom: 0;
        }

        .zsa-page-content .zsa-btn {
            height: 36px;
            padding: 0 12px;
        }

        .layui-form-pane div[pane] {
            position: relative;
            border: 1px solid #e6e6e6;
        }
    </style>
</head>
<body class="childrenBody">
<ul class="layui-nav layui-nav-tree layui-nav-side zsa-nav">
    <li class="layui-nav-item zsa-nav-title">部门/小组 列表</li>
    <ul id="role-container" class="tree_contianer"></ul>
</ul>
<div class="zsa-page-content">
    <div class="layui-tab" lay-filter="page-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">用户管理</li>
            <li>部门管理</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show" id="users-tab-item">
                <div class="layui-row">
                    <div class="layui-col-sm6" style="padding-right: 10px">
                        <div id="binding-search-container"></div>
                        <table id="binding-user-table" lay-filter="binding-user-table"></table>
                    </div>
                    <div class="layui-col-sm6" style="padding-left: 10px">
                        <div id="not-search-container"></div>
                        <table id="not-user-table" lay-filter="not-user-table"></table>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item" id="department-tab-item">
                <div class="layui-tab" lay-filter="department-tab">
                    <ul class="layui-tab-title">
                        <li class="layui-this">子部门列表</li>
                        <li>部门详细</li>
                    </ul>
                    <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show" id="list-tab-item">
                            <div id="department-seach-container"></div>
                            <table id="department-table" lay-filter="department-table"></table>
                        </div>
                        <div class="layui-tab-item" id="detailed-tab-item">
                            <form class="layui-form layui-form-pane" lay-filter="detailed-form"
                                  onsubmit="return false;">
                                <input type="hidden" class="zsa-hidden-id" name="id">
                                <input type="hidden" name="parentId">
                                <input type="hidden" name="type" value="102">
                                <div class="layui-row layui-col-space10 layui-form-item">
                                    <div class="layui-col-md12">
                                        <label class="layui-form-label">部门/小组 名</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="name" class="layui-input" lay-verify="required">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">序号</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="sort" value="0" placeholder="请输入排序号"
                                               lay-verify="required|number"
                                               class="layui-input userPhone">
                                    </div>
                                </div>
                                <div class="layui-row layui-col-space10 layui-form-item">
                                    <div class="layui-col-md12">
                                        <label class="layui-form-label">有效</label>
                                        <div class="layui-input-block" pane>
                                            <input type="checkbox" name="state" lay-skin="switch" lay-text="有效|无效">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item layui-form-text">
                                    <label class="layui-form-label">备注</label>
                                    <div class="layui-input-block">
                                        <textarea name="remark" placeholder="请输入备注内容"
                                                  class="layui-textarea myself"></textarea>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <!--<div class="layui-input-block">-->
                                    <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                    <!--</div>-->
                                </div>
                            </form>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="sys_toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="sys_toolbar_search">搜索</button>
    <button class="layui-btn layui-btn-sm" lay-event="sys_toolbar_refresh">
        <i class="layui-icon" style="line-height:30px">&#xe669;</i>
    </button>
</script>
<script type="text/html" id="binding-bar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="untie"><i class="layui-icon">&#x1006;</i>解绑&nbsp;</a>
</script>
<script type="text/html" id="not-bar">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="binding"><i
            class="layui-icon">&#xe605;</i>绑定&nbsp;</a>
</script>

<script type="text/html" id="sys_department_toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="sys_toolbar_search">搜索</button>
    <button class="layui-btn layui-btn-sm" lay-event="sys_toolbar_refresh">
        <i class="layui-icon" style="line-height:30px">&#xe669;</i>
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="sys_toolbar_add">
        <i class="layui-icon" style="line-height:30px">&#xe654;</i>添加
    </button>
</script>

<script type="text/html" id="department_toolDemo">
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon">&#xe640;</i>删除</a>
</script>

<div th:replace="authority/common/currency/footer"></div>
<script>

    layui.extend({
        complexSearch: 'complexSearch/complexSearch' // {/}的意思即代表采用自有路径，即不跟随 base 路径
        , dtree: 'dtree/dtree'
    });
    layui.link(layui.cache.base + 'dtree/dtree.css?v=' + (layui.cache.version ? layui.cache.version : '1'));
    layui.link(layui.cache.base + 'dtree/font/dtreefont.css?v=' + (layui.cache.version ? layui.cache.version : '1'));
    layui.use(['lutil', 'form', 'table', 'element', 'complexSearch', 'dtree'], function () {
        var form = layui.form, dtree = layui.dtree, lutil = layui.lutil, element = layui.element
            , layer = layui.layer, table = layui.table, complexSearch = layui.complexSearch;

        var binding_search = complexSearch.render({
            container: "#binding-search-container",
            isDynamic: false,
            submit: false,
            returnFormat: {
                dataTypeName: 'type'
            },
            data: [
                {field: 'name', title: '姓名', editType: 'text', dataType: 'string', formulas: ['<->']},
            ],
            search: function (data) {
                var binding_table = layui.pageObtainTable('binding-user-table');
                binding_table && binding_table.query({searchs: data.length > 0 ? JSON.stringify(data) : ''});
            }
        });
        var not_search = complexSearch.render({
            container: "#not-search-container",
            isDynamic: false,
            submit: false,
            returnFormat: {
                dataTypeName: 'type'
            },
            data: [
                {field: 'name', title: '姓名', editType: 'text', dataType: 'string', formulas: ['<->']},
            ],
            search: function (data) {
                var not_table = layui.pageObtainTable('not-user-table');
                not_table && not_table.query({searchs: data.length > 0 ? JSON.stringify(data) : ''});
            }
        });
        var roleData, treeFindData = function (data, id) {
            var result = undefined;
            return $.each(data, function (i, e) {
                if (id == e['id']) return result = e, false;
                if (e['children']) if (!(result = treeFindData(e['children'], id))) return false;
            }), result;
        };
        var roleTree = dtree.render({
            elem: "#role-container",
            icon: "1",
            skin: "layui",
            headers: {'[[${_csrf.headerName}]]': '[[${_csrf.token}]]'},
            url: content_path + 'authority/department/department_tree.do',
            dataStyle: "layuiStyle",
            response: {statusCode: 0, title: 'name'},
            parseData: function (data) {
                roleData = $.extend({}, data, true);
                return data;
            }
        });
        dtree.on("node('role-container')", function (res) {
            var param = res.param;
            if ($("#users-tab-item").hasClass("layui-show")) {
                var binding_table = layui.pageObtainTable('binding-user-table'),
                    not_table = layui.pageObtainTable('not-user-table');
                binding_table && binding_table.query({roleId: param['nodeId']}), not_table && not_table.query({roleId: param['nodeId']});
            } else {
                if ($("#list-tab-item").hasClass("layui-show")) {
                    var department_table = layui.pageObtainTable("department-table");
                    department_table && department_table.query({id: param['nodeId']});
                } else {
                    param['nodeId'] && updateForm(param['nodeId']);
                }
            }
            var tab = $('div.layui-tab[lay-filter=department-tab] ul li[lay-id=tab-add-0000]');
            if (tab.length) tab.find('i.layui-tab-close').click();
        });

        table.set({
            method: 'POST',
            defaultToolbar: [],
            cellMinWidth: '100',
            page: true,
            limit: 10,
            limits: [5, 10, 20, 30, 50],
            text: {
                none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
            },
            even: true,
            // skin: 'line',
            headers: {'[[${_csrf.headerName}]]': '[[${_csrf.token}]]'},
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            response: {
                // statusName: 'success' //数据状态的字段名称，默认：code 加上有问题
                statusCode: 0 //成功的状态码，默认：0
                , msgName: 'message' //状态信息的字段名称，默认：msg
                , countName: 'total' //数据总数的字段名称，默认：count
                , dataName: 'data' //数据列表的字段名称，默认：data
            }
        });
        var binding_height = $(window).height() - $('#binding-seach-container').outerHeight() - 65,
            binding_height_value = parseInt(binding_height) > 300 ? parseInt(binding_height) : 300;
        layui.page_table_examples.push(table.render({
            elem: '#binding-user-table',
            url: content_path + 'authority/role/role_users.do',
            height: binding_height_value,
            toolbar: '#sys_toolbarDemo',
            title: '用户列表',
            where: {type: 1},
            cols: [
                [//标题栏
                    {type: 'checkbox', fixed: 'left'},
                    // {field: 'id', title: 'ID', fixed: 'left', width: 100},
                    {field: 'name', title: '用户名', sort: true, fixed: 'left', width: 150},
                    {field: 'account', title: '账号', sort: true, width: 100},
                    {
                        field: 'sex', title: '性别', sort: true, templet: function (d) {
                            return '<span>' + (d.sex == 0 ? '女' : '男') + '</span>';
                        }, align: 'center', width: 65
                    },
                    {field: 'idCard', title: '身份证号码', minWidth: 150},
                    {field: 'phone', title: '手机号码', minWidth: 110},
                    {field: 'cz', title: '操作', width: 90, toolbar: "#binding-bar", fixed: 'right', align: 'center'}
                ]
            ]
        }));

        var not_height = $(window).height() - $('#not-seach-container').outerHeight() - 65,
            not_height_value = parseInt(not_height) > 300 ? parseInt(not_height) : 300;
        layui.page_table_examples.push(table.render({
            elem: '#not-user-table',
            url: content_path + 'authority/role/role_users.do',
            height: not_height_value,
            toolbar: '#sys_toolbarDemo',
            title: '用户列表',
            where: {type: 0},
            cols: [
                [//标题栏
                    {type: 'checkbox', fixed: 'left'},
                    // {field: 'id', title: 'ID', fixed: 'left', width: 100},
                    {field: 'name', title: '用户名', sort: true, fixed: 'left', width: 150},
                    {field: 'account', title: '账号', sort: true, width: 100},
                    {
                        field: 'sex', title: '性别', sort: true, templet: function (d) {
                            return '<span>' + (d.sex == 0 ? '女' : '男') + '</span>';
                        }, align: 'center', width: 65
                    },
                    {field: 'idCard', title: '身份证号码', minWidth: 150},
                    {field: 'phone', title: '手机号码', minWidth: 110},
                    {field: 'cz', title: '操作', width: 90, toolbar: "#not-bar", fixed: 'right', align: 'center'}
                ]
            ]
        }));

        var department_search = complexSearch.render({
            container: "#department-seach-container",
            isDynamic: false,
            submit: false,
            data: [
                {field: 'name', title: '部门名称', editType: 'text', formula: '<->'},
                {field: 'remark', title: '备注', editType: 'text', formula: '<->'},
                {
                    field: 'state',
                    title: '状态',
                    editType: 'select',
                    formula: '=',
                    options: [{key: '--请选择--', value: ''}, {key: '有效', value: '1'}, {key: '无效', value: '0'}]
                },
            ],
            search: function (data) {
                $.each(data, function (i, e) {
                    if (e['editType']) e['type'] = e['editType'], delete e['editType'];
                });
                var thisTable = layui.pageObtainTable('department-table');
                thisTable && thisTable.query({searchs: data.length > 0 ? JSON.stringify(data) : ''});
            }
        });
        var height = $(window).height() - $('#role-seach-container').outerHeight() - 85,
            height_value = parseInt(height) > 300 ? parseInt(height) : 300;
        layui.page_table_examples.push(table.render({
            elem: '#department-table',
            url: content_path + 'authority/department/list.do',
            height: height_value,
            toolbar: '#sys_department_toolbarDemo',
            title: '部门列表',
            cols: [
                [//标题栏
                    {type: 'checkbox', fixed: 'left'},
                    // {field: 'id', title: 'ID', fixed: 'left', width: 100},
                    {field: 'name', title: '部门名称', sort: true, fixed: 'left', width: 150},
                    {field: 'code', title: '代码', fixed: 'left', width: 150},
                    {field: 'sort', title: '排序', sort: true, width: 80},
                    {field: 'remark', title: '备注', minWidth: 250},
                    {field: 'modifiedUser', title: '最后修改人', hide: true, sort: true, width: 100},
                    {field: 'modifiedTime', title: '最后修改时间', hide: true, sort: true, align: 'center', width: 150},
                    {
                        field: 'state', title: '状态', templet: function (d) {
                            return '<input type="checkbox" name="state" lay-filter="field_state" value="' + d.id + '" lay-skin="switch" zsa-val-format="[1,0]" lay-text="正常|失效"' + (d.state == 1 ? 'checked' : '') + '>';
                        }, sort: true, fixed: 'right', width: 90, align: 'center'
                    },
                    {
                        field: 'cz',
                        title: '操作',
                        width: 90,
                        toolbar: "#department_toolDemo",
                        fixed: 'right',
                        align: 'center'
                    }
                ]
            ]
        }));

        $.each(layui.page_table_examples, function (i, e) {
            var id = e.config.id || e.config.index;
            if (!id) return true;
            table.on('sort(' + id + ')', function (obj) {
                e && e.sort(obj);
            });
            table.on('toolbar(' + id + ')', function (obj) {
                var checks = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'sys_toolbar_refresh':
                        e && e.refresh();
                        break;
                    case 'sys_toolbar_search':
                        var search;
                        switch (id) {
                            case 'binding-user-table':
                                search = binding_search;
                                break;
                            case 'not-user-table':
                                search = not_search;
                                break;
                            case 'department-table':
                                search = department_search;
                                break;
                        }
                        search.submit();
                        break;
                    case 'sys_toolbar_add':
                        var check = dtree.getNowParam(roleTree),
                            roleid = check && check['nodeId'] ? check['nodeId'] : '';
                        if (roleid == undefined || roleid == '') return lutil.error_alert('没有选择父节点'), false;
                        var tab = $('#department-tab-item div.layui-tab[lay-filter=department-tab] ul li[lay-id=tab-add-0000]');
                        if (tab.length != 0) tab.find('input[type=hidden][name=parentId]').val(roleid), tab.click();
                        var add_from = $($('form[lay-filter=detailed-form]').prop('outerHTML'))
                            , id_input = add_from.find('input.zsa-hidden-id[type=hidden][name=id]');
                        add_from.attr('lay-filter', 'add-form');
                        // if (id_input.val() == undefined || id_input.val() == '') return lutil.error_alert('没有选择父节点'), false;
                        add_from.find('input[type=hidden][name=parentId]').val(roleid);
                        id_input.remove();
                        add_from[0].reset();
                        element.tabAdd('department-tab', {
                            title: '新增角色'
                            , content: add_from.prop('outerHTML') //支持传入html
                            , id: 'tab-add-0000'
                        });
                        tab = $('#department-tab-item div.layui-tab[lay-filter=department-tab] ul li[lay-id=tab-add-0000]');
                        var close = $('<i class="layui-icon layui-unselect layui-tab-close">&#x1006;</i>');
                        tab.append(close);
                        close.click(function () {
                            element.tabDelete('department-tab', 'tab-add-0000');
                        });
                        form.render(null, 'add-form');
                        tab.click();
                        break;
                }
            });
            table.on('tool(' + id + ')', function (obj) {
                var data = obj.data; //获得当前行数据
                switch (obj.event) {
                    case 'untie':
                    case 'binding':
                        var where = e.getParams();
                        var load = layer.load(1), params = {
                            roleId: where.roleId,
                            userIds: obj.data.id,
                            type: obj.event
                        };
                        var successFunc = function () {
                                dtree.reload(roleTree, {async: false}), dtree.dataInit(roleTree, where.roleId);
                                $.each(layui.page_table_examples, function (i, item) {
                                    if ((e.config.id || e.config.index).indexOf('-user-table') > 0) item && item.refresh();
                                })
                            },
                            completeFunc = function () {
                                layer.close(load);
                            };
                        ajaxRequestByCsrf(content_path + 'authority/department/change_user_rel.do', params, successFunc, null, completeFunc);
                        break;
                    case 'del':
                        lutil.my_confirm("确定要删除“" + data['name'] + "”？？", function () {
                            var load = layer.load(2, {shade: [0.3, '#eee']});
                            ajaxRequestByCsrf(content_path + "authority/department/del.do", {id: data['id']}, function (res) {
                                var thisTable = layui.pageObtainTable('department-table');
                                dtree.reload(roleTree, {async: false}), dtree.dataInit(roleTree, data['parentId']), thisTable && thisTable.refresh();
                            }, null, function () {
                                layer.close(load);
                            })
                        })
                        break;
                }
            });
        });

        element.on('tab(department-tab)', function (data) {
            var check = dtree.getNowParam(roleTree), roleid = check && check['nodeId'] ? check['nodeId'] : ''
                , treeNodeData = treeFindData(roleData, roleid);
            // if (!treeNodeData || treeNodeData['isFirst']) roleid = '';
            if ($("#list-tab-item").hasClass("layui-show")) {
                var department_table = layui.pageObtainTable("department-table");
                department_table && department_table.query({id: roleid});
            } else {
                roleid && updateForm(roleid);
            }
        });

        element.on('tab(page-tab)', function (data) {
            var check = dtree.getNowParam(roleTree), roleid = check && check['nodeId'] ? check['nodeId'] : ''
                , treeNodeData = treeFindData(roleData, roleid);
            // if (!treeNodeData || treeNodeData['isFirst']) roleid = '';
            if ($("#users-tab-item").hasClass("layui-show")) {
                var binding_table = layui.pageObtainTable('binding-user-table'),
                    not_table = layui.pageObtainTable('not-user-table');
                binding_table && binding_table.query({roleId: roleid}), not_table && not_table.query({roleId: roleid});
            } else {
                if ($("#list-tab-item").hasClass("layui-show")) {
                    var department_table = layui.pageObtainTable("department-table");
                    department_table && department_table.query({id: roleid});
                } else {
                    roleid && updateForm(roleid);
                }
            }
        });


        function updateForm(id) {
            var load = layer.load(2, {shade: [0.3, '#eee']});
            ajaxRequestByCsrf(content_path + "authority/role/detailed.do", {id: id}, function (res) {
                form.val("detailed-form", res.data);
            }, null, function () {
                layer.close(load);
            })
        }

        form.on('submit(submit)', function (data) {
            var load = layer.load(2, {shade: [0.3, '#eee']});
            if (data.field['state']) data.field['state'] = data.field['state'] == 'on' ? 1 : 0; else data.field['state'] = 0;
            if (data.field['intercept']) data.field['intercept'] = data.field['intercept'] == 'on' ? 1 : 0; else data.field['intercept'] = 0;
            ajaxRequestByCsrf(content_path + "authority/department/add.do", data.field, function (res) {
                var thisTable = layui.pageObtainTable('department-table'),
                    tab = $('#department-tab-item div.layui-tab[lay-filter=department-tab] ul li[lay-id=tab-add-0000]');
                if (tab.length) tab.find('i.layui-tab-close').click();
                if (data.field['id']) updateForm(data.field['id']);
                else dtree.reload(roleTree, {async: false}), dtree.dataInit(roleTree, data['parentId'])
                    , thisTable && thisTable.refresh(), tab.length && tab.find('i.layui-tab-close').click();
            }, null, function () {
                layer.close(load);
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    })

</script>
</body>
</html>